var Bind = function(object, fun) {
    return function() {
        return fun.apply(object, arguments);
    }
}
function AutoComplete(id,arr){
	this.uid = id;
    this.obj=document.getElementById(id+"_input");        //输入框
    this.autoObj=document.getElementById(id+"_auto");//DIV的根节点
    this.showDiv=document.getElementById(id+"_div");//显示值的div
    this.value_arr=arr;        //不要包含重复值
    this.index=-1;          //当前选中的DIV的索引
    this.search_value="";   //保存当前搜索的字符
}


var told ;
var timeold ;
function runAutoComp(autoCompObj,env){
	if(event.keyCode==13){
		setTimeout(function(){
			setValueByInput(autoCompObj);
		},300);
	}else{
		if(!timeold){
			timeold = new Date().getTime();
		}else{
			var now = new Date().getTime();
			if(now-timeold<500){
				clearTimeout(told);
			}
			timeold = now;
		}
		told = setTimeout(function(){
			autoCompObj.start(env);
		},100);
	}
}

/**
 * 
 * @param {Object} autoCompObj
 * @param {Object} jsonArr  再次加载时从后台获取的json数组
 * @return {TypeName} 
 */
function setValueByInput(autoCompObj,jsonArr){
	var _this = autoCompObj;
	var e = $(_this.obj).val();
	_this.obj.value="";
    _this.autoObj.className="auto_hidden";
    var validate = /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/;
    var pdiv = $(_this.showDiv);
    if(!jsonArr){//手动输入
	    if(e==""){
			return;
		} 
	    var ems = $(".emailDiv",pdiv);
	    for(var i=0;i<ems.length;i++){
	    	var em = $(ems[i]).attr("email");
	    	if(em==e){
	    		return;
	    	}
	    }
	    var arr = e.split(",");
	    for(var i=0;i<arr.length;i++){
	    	 var v = arr[i];
	    	 if(v==""){
	    		 continue;
	    	 }
			 if(!validate.test(v)){        
				 classname ='mailAdError'
			 }else{
				 classname ='mailAdOK'
			 }
			 var befName = v;
			 var index = befName.indexOf("@");
			 if(index!=-1){
				 befName = befName.substring(0,index);
			 }
		     pdiv.append("<div class='emailDiv "+classname+"' email=\""+v+"\">"+befName+"&lt;"+v+"&gt;<div onclick='delemail(this)' class='delemail'><img src='/mobilemode/apps/e-cology/email/imgs/del.png'></div></div>");
	    }
    }else{
    	$(_this.showDiv).html("");
    	var arr = jsonArr;
    	
	    for(var i=0;i<arr.length;i++){
	    	 var v = arr[i]["name"];
	    	 var showname = arr[i]["showname"];
	    	 if(v==""){
	    		 continue;
	    	 }
			 if(!validate.test(v)){        
				 classname ='mailAdError'
			 }else{
				 classname ='mailAdOK'
			 }
		     pdiv.append("<div class='emailDiv "+classname+"' email=\""+v+"\">"+showname+"<div onclick='delemail(this)' class='delemail'><img src='/mobilemode/apps/e-cology/email/imgs/del.png'></div></div>");
	    }
    }
}

function delemail(obj){
	$(obj).parent().remove();
}

function log(str){
	if(console){
		console.log("log:"+str);
	}
}

AutoComplete.prototype={
    //初始化DIV的位置
    init: function(){
        this.autoObj.style.left = this.obj.offsetLeft + "px";
        this.autoObj.style.top  = (this.obj.offsetTop + this.obj.offsetHeight-$("#detailContentEdit")[0].offsetTop) + "px";
        this.autoObj.style.width= this.obj.offsetWidth - 2 + "px";//减去边框的长度2px   
    },
    //删除自动完成需要的所有DIV
    deleteDIV: function(){
        while(this.autoObj.hasChildNodes()){
            this.autoObj.removeChild(this.autoObj.firstChild);
        }
        this.autoObj.className="auto_hidden";
    },
    //设置值
    setValue: function(_this){
        return function(){
            _this.obj.value="";
            _this.autoObj.className="auto_hidden";
            
            var pdiv = $(_this.showDiv);
            var ems = $(".emailDiv",pdiv);
            for(var i=0;i<ems.length;i++){
            	var em = $(ems[i]).attr("email");
            	if(em==this.seq){
            		return;
            	}
            }
             var validate = /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/;
			 if(!validate.test(this.seq)){        
				 classname ='mailAdError'
			 }else{
				 classname ='mailAdOK'
			 }
             pdiv.append("<div class='emailDiv "+classname+"' email=\""+this.seq+"\">"+this.ename+"&lt;"+this.seq+"&gt;<div onclick='delemail(this)' class='delemail'><img src='/mobilemode/apps/e-cology/email/imgs/del.png'></div></div>");
        }       
    },
    //模拟鼠标移动至DIV时，DIV高亮
    autoOnmouseover: function(_this,_div_index){
        return function(){
            _this.index=_div_index;
            var length = _this.autoObj.children.length;
            for(var j=0;j<length;j++){
                if(j!=_this.index ){       
                    _this.autoObj.childNodes[j].className='auto_onmouseout';
                }else{
                    _this.autoObj.childNodes[j].className='auto_onmouseover';
                }
            }
        }
    },
    //更改classname
    changeClassname: function(length){
        for(var i=0;i<length;i++){
            if(i!=this.index ){       
                this.autoObj.childNodes[i].className='auto_onmouseout';
            }else{
                this.autoObj.childNodes[i].className='auto_onmouseover';
                this.obj.value=this.autoObj.childNodes[i].seq;
            }
        }
    }
    ,
    //程序入口
    start: function(event){
        if(event.keyCode!=13&&event.keyCode!=38&&event.keyCode!=40){
            this.init();
            this.deleteDIV();
            if(this.obj.value.replace(/(^\s*)|(\s*$)/g,'')==""){ return; }//值为空，退出
            this.search_value=this.obj.value;
            var url = "/cloudstore/app/no0000094/jsp/EmailOperation.jsp?userid="+userid+"&operation=getEmailLxr";
			var param = "&q="+this.obj.value;
			url += param;
			var autoObject = this;
			$.get(url, function(responseText){
				var data = $.parseJSON(responseText);
	            var valueArr=data["dataArr"];
	            var div_index=0;//记录创建的DIV的索引
				autoObject.deleteDIV();
	            for(var i=0;i<valueArr.length&&div_index<5;i++){
	            	var indexObj = valueArr[i];
	            	var email = indexObj["to"];
	            	var name = indexObj["name"];
                    var div = document.createElement("div");
                    div.className="auto_onmouseout";
                    div.seq=email;
                    div.ename=name;
                    div.onclick=autoObject.setValue(autoObject);
                    div.onmouseover=autoObject.autoOnmouseover(autoObject,div_index);
                    div.innerHTML=(name+"&lt;"+email+"&gt;");
                    autoObject.autoObj.appendChild(div);
                    autoObject.autoObj.className="auto_show";
                    div_index++;
	            }
			});
        }
        window.onresize=Bind(this,function(){this.init();});
    }
}